package top.jacktgq.hsp.nio.buffer_channel;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * @Author CandyWall
 * @Date 2020/11/11--12:06
 * @Description 使用FileChannel从文件中读取数据
 */
public class NIOFileChannel02 {
    public static void main(String[] args) {
        String str = "hello，糖果墙";
        //创建一个文件输入流
        FileInputStream fis = null;
        try {
            fis = new FileInputStream(new File("tmp/file01.txt"));

            //通过FileInputStream获取对应的FileChannel，实际类型是FileChannelImpl
            FileChannel fileChannel = fis.getChannel();

            //创建一个缓冲区 ByteBuffer
            ByteBuffer byteBuffer = ByteBuffer.allocate(1024);

            //将通道的数据读入到ByteBuffer中
            fileChannel.read(byteBuffer);

            //将byteBuffer字节转成字符串
            System.out.println(new String(byteBuffer.array(), "utf-8"));

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                fis.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
